package com.rtx.wms.std.handler.po.down;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rtx.wms.std.asn.bean.Receipt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.asn.bean.Receiptdetail;
import com.rtx.wms.std.asn.service.ReceiptService;
import com.rtx.wms.std.po.bean.ApiCarton;
import com.rtx.wms.std.po.bean.ApiPo;
import com.rtx.wms.std.po.bean.ApiPodetail;
import com.rtx.wms.std.po.bean.Po;
import com.rtx.wms.std.po.bean.Podetail;
import com.rtx.wms.std.po.bean.RtxCarton;
import com.rtx.wms.std.po.service.ApiPoService;
import com.rtx.wms.std.po.service.PoService;
import com.rtx.wms.std.po.service.PodetailService;
import com.rtx.wms.std.po.service.RtxCartonService;

/**
 * 格瑞普 po单创建
 * @author Administrator
 *
 */
@Component
public class GrpPoDownHandle extends AbsPoDownHandle{
	
	@Autowired
	RtxCartonService rtxCartonService;
	
	@Autowired
	ApiPoService apiPoService;
	
	@Autowired
	ReceiptService receiptService;
	
	@Autowired
	PoService poService;
	
	
	@Autowired
	PodetailService podetailService;

	
	//存在
	public void handelExistsPo(ApiPo apipo,Po po,EdiInnerRequestDTO dto) {
		//SELECT 1 FROM RECEIPTDETAIL WHERE POKEY ='接口外部单号'
		LambdaQueryWrapper<Receiptdetail> receiptdetailqw = Wrappers.lambdaQuery();
		receiptdetailqw.eq(Receiptdetail::getPokey, po.getPokey());
		List<Receiptdetail> receiptdetailList = receiptService.selectReceiptDetailByWrapper(po.getWhseid(), receiptdetailqw);
	    LambdaQueryWrapper<Podetail> poqw = Wrappers.lambdaQuery();
    	poqw.eq(Podetail::getPokey, po.getPokey());
    	List<Podetail> polist =  podetailService.queryByWrappPodetail(po.getWhseid(), poqw);

		// 不存在数据，根据'接口外部单号'+'PO外部行号'，更新PO明细
		if(CollectionUtils.isEmpty(receiptdetailList)){
			poService.deletePoAndDetail(apipo.getWhseid(), po.getPokey(),apipo.getExternpokey());
			createPO(apipo,dto);
			/*List<ApiPodetail> newPodetailList = new ArrayList<>();
			List<Podetail> updPodetailList = new ArrayList<>();

			// po明细中是否存在，存在的更新，不存在的新增
			for(ApiPodetail pitem:apipo.getPodetail()) {
				List<Podetail> poFilterist  = polist
						.stream()
						.filter(temp->
								pitem.getExternlineno().equals(temp.getExternlineno())&&
										pitem.getSku().equals(temp.getSku())
						).collect(Collectors.toList());
				if(poFilterist.size() < 1) {
					//新增行项
					newPodetailList.add(pitem);
				}else {
					//修改行项
					for(Podetail existsItem:poFilterist) {
						BeanUtils.copyProperties(pitem, existsItem);
						existsItem.setQtyreceived(null);
						existsItem.setStatus(null);
						updPodetailList.add(existsItem);
					}
				}
			}
			//新增
			if(newPodetailList.size() > 0) {
				poService.addExistsPodetail(po.getWhseid(), po, newPodetailList, apipo);
			}
			//修改
			if(updPodetailList.size()> 0) {
				//更新po以及po明细
				poService.updPoAndPodetail(apipo.getWhseid(),po,apipo, updPodetailList);
			}*/
			// 状态修改
			this.chengStatus(po);
		}else{
			String receiptKey = receiptdetailList.get(0).getReceiptkey();
			//存在数据，查询出对应状态RECEIPT，STATU
			String status = receiptService.selectReceiptStatusByWrapper(apipo.getWhseid(), receiptKey);
			// 当RECEIPT.STATUS大于0，小于11已结，报错
			int statusInt = Integer.parseInt(status);
			if(statusInt > 0 && statusInt < 11){
				throw new RuntimeException("PO单"+po.getExternpokey()+"正在收货中，请进行回转收货");
			}
			//当RECEIPT.STATUS等于0，删除对应PO单+ASN单，创建PO单
			if(statusInt == 0){
				poService.deletePoAndAsn(apipo.getWhseid(), po.getPokey(), receiptKey,apipo.getExternpokey());
				createPO(apipo,dto);
			}
			//当RECEIPT.STATUS大于等于11，根据接口外部单号+接口外部行号+接口数量，对比PO明细
			if(statusInt >= 11){
				List<ApiPodetail> newPodetailList = new ArrayList<>();
				List<Podetail> updPodetailList = new ArrayList<>();
				// 当接口数量大于PO明细中的接收量，根据接口数量更新PO明细订购量
				// 当接口数量小于等于PO明细中的接收量，报错
				for(ApiPodetail poitem : apipo.getPodetail()) {
					List<Podetail> poFilterist  = polist
							.stream()
							.filter(temp->
									poitem.getExternlineno().equals(temp.getExternlineno())&&
											poitem.getSku().equals(temp.getSku())
							).collect(Collectors.toList());
					if(poFilterist.size() < 1) {
						//新增行项
						newPodetailList.add(poitem);
					}else {
						//修改行项
						for(Podetail existsItem:poFilterist) {
							// 接口数量
							Double openqtyDown = Double.parseDouble(poitem.getQtyordered());
							// PO明细接收量
							Double qtyreceivedExists = Double.parseDouble(existsItem.getQtyreceived());
							if(Double.compare(openqtyDown, qtyreceivedExists) <= 0) {
								throw new RuntimeException("下发数量小于等于已收数量!");
							}else{
								BeanUtils.copyProperties(poitem, existsItem);
								existsItem.setQtyreceived(null);
								existsItem.setStatus(null);
								existsItem.setRtx_erpokey(poitem.getRtxErpokey());
								updPodetailList.add(existsItem);
							}
						}
					}
				}
				//新增
				if(newPodetailList.size() > 0) {
					poService.addExistsPodetail(po.getWhseid(), po, newPodetailList, apipo);
				}
				//修改
				if(updPodetailList.size()> 0) {
					//更新po以及po明细
					poService.updPoAndPodetail(apipo.getWhseid(), po,apipo, updPodetailList);
				}
				// 状态修改
				this.chengStatus(po);
			}
		}
	}
	
	
	
	public void handelNotExistsPo(ApiPo apipo,EdiInnerRequestDTO dto) {
		createPO(apipo,dto);
	}
	
	//创建单 
	public void createPO(ApiPo apipo,EdiInnerRequestDTO dto) {
		if("1".equals(apipo.getToexamine())) {
			List<ApiCarton> list =	apipo.getCarton().stream().filter(temp->StringUtils.hasLength(temp.getExternlineno())).collect(Collectors.toList());
			if(CollectionUtils.isEmpty(list)) {
				throw new RuntimeException("当前已审核单无收货箱数据");
			}
		}
		
		apiPoService.insertApiPoAndpoDetailAndCartonid("ris_edi", apipo);
	}

	//状态更新
	public void chengStatus(Po po){
		String status = "";

		LambdaQueryWrapper<Podetail> poqw = Wrappers.lambdaQuery();
		poqw.eq(Podetail::getPokey, po.getPokey());
		List<Podetail> polist =  podetailService.queryByWrappPodetail(po.getWhseid(), poqw);
		
		String poStatus = "";
		//表头未结量
		Double openqty = Double.parseDouble(po.getOpenqty());
		
		// 接收量
		Double qtyreceived = polist.stream().mapToDouble(item -> Double.parseDouble(item.getQtyreceived())).sum();

		// 订购量
		Double qtyordered = polist.stream().mapToDouble(item -> Double.parseDouble(item.getQtyordered())).sum();

		//接收量为0，新建0
		if(Double.compare(qtyreceived, 0D) == 0){
			status = "0";
			poStatus = "0";
		}
		//接收量小于订购量，收货中5
		if(Double.compare(qtyreceived, qtyordered) < 0){
			status = "5";
			poStatus = "5";
		}
		//接收量等于订购量，收货完成9
		if(qtyreceived > 0D && Double.compare(qtyreceived, qtyordered) == 0){
			status = "9";
			poStatus = "9";
		}
		
		if(Double.compare(openqty, qtyordered) ==0 ) {
			poStatus = "0";
		}

		// 明细更新状态
		poService.updPodetailStatus(po.getWhseid(), po.getPokey(), status);
		
		// 表头更新状态
		poService.updPoStatus(po.getWhseid(), po.getPokey(), poStatus);
	}
	
	//校验箱明细
	@Override
	protected void checkRtxCarton(ApiPo apipo,EdiInnerRequestDTO dto) {
		for(ApiCarton carton:apipo.getCarton()) {
			LambdaQueryWrapper<RtxCarton> qw = Wrappers.lambdaQuery();
			//qw.eq(RtxCarton::getExternpokey, carton.getExternpokey());
			qw.eq(RtxCarton::getId, carton.getId());
			qw.eq(RtxCarton::getStatus, "0");
			boolean exists = rtxCartonService.checkExists(apipo.getWhseid(), qw);
			if(exists) {
				throw new RuntimeException("箱号-"+carton.getId()+"-重复下发");
			}
		}
	}

	/**
	 * 
	 */
	@Override
	protected void preinsert(ApiPo r, HttpServletRequest request) {
		
	}
}
